<template>
  <div class="app-container">
    <page-tools :show-before="true">
      <template v-slot:before>
        <span>共{{ page.total }}条记录 </span>
      </template>
      <template slot="after">
        <el-button size="small" type="danger" @click="exportMutiData">excel导出</el-button>
        <el-button size="small" type="success" @click="$router.push('/import')">excel导入</el-button>
        <el-button size="small" type="primary" @click="showDialog = true" :disabled="!checkPermission('add-user')">新增员工</el-button>
      </template>
    </page-tools>

    <!-- 表格和分页 -->
    <el-card>
      <el-table :data="list" border stripe v-loading="loading">
        <el-table-column
          label="序号"
          sortable
          align="center"
          width="80"
          type="index"
        />
        <el-table-column prop="username" label="姓名" sortable />
        <el-table-column align="center" label="头像" sortable >
          <template slot-scope="{ row }">
            <img 
          :src="row.staffPhoto" 
          style="border-radius: 50%; width: 100px; height: 100px; padding: 10px"
          v-imageerror="require('@/assets/common/bigUserHeader.png')"
          @click="showQrCode(row.staffPhoto)"
          >
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" sortable />
        <el-table-column prop="workNumber" label="工号" sortable />
        <el-table-column
          prop="formOfEmployment"
          label="聘用形式"
          sortable
          :formatter="formatEmployment"
        />
        <el-table-column prop="departmentName" label="部门" sortable />
        <el-table-column prop="timeOfEntry" label="入职时间" sortable>
          <template slot-scope="{ row }">
            {{ row.timeOfEntry | formatDate }}
          </template>
        </el-table-column>
        <el-table-column prop="enableState" label="状态" sortable>
          <template slot-scope="{ row }">
            <el-switch :value="row.enableState === 1" />
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="操作"
          sortable
          fixed="right"
          width="280"
        >
          <template slot-scope="{ row }">
            <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="asingRole(row.id)">角色</el-button>
            <el-button type="text" size="small" :disabled="!checkPermission('del-user')" @click="delEmployee(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
        <el-pagination
          :total="page.total"
          :page-size="page.size"
          :current-page.sync="page.page"
          @current-change="getEmployeesList"
          layout="total,prev ,pager,next"
        ></el-pagination>
      </el-row>
    </el-card>
    <!-- 新增员工弹层组件 -->
    <add-employee :show-dialog.sync="showDialog" />
    <!-- 二维码弹层 -->
    <el-dialog title="二维码" :visible.sync = 'showCodeDialog' >
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>

    <!-- 角色弹层 -->
    <asign-role ref="asignRole" :user-id= "userId" :show-role-dialog.sync="showRoleDialog" />

  </div>
</template>

<script>
import { getEmployeesList, delEmployee } from "@/api/employees";
import EmployeeEnum from "@/api/constant/employees";
import AddEmployee from "./components/add-employee.vue";
import { formatDate } from '@/filters'
import QrCode from 'qrcode'
import AsignRole from './components/asign-role'
export default {
  name: "My-Emplouees",
  components: {
    AddEmployee,
    AsignRole
  },
  data() {
    return {
      loading: false,
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: null,
      page: {
        page: 1,
        total: 0,
        size: 10,
      },
      list: [],
    };
  },
  created() {
    this.getEmployeesList();
  },
  methods: {
    // 显示二维码
    showQrCode(url){
      if(url && url.trim()) {
        this.showCodeDialog = true
        // this.$nextTick() 总是等到当前数据更新完毕并渲染完毕后执行
        // this.$nextTick(() => { }) 
        setTimeout(()=>{
          QrCode.toCanvas(this.$refs.myCanvas,url)
        },0)
      }else {
        this.$message.warning('当前用户未设置头像')
      }
    },
    // excel文件导出
    exportMutiData(){
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 懒加载模块，只有点击之后才会加载
      import('@/vendor/Export2Excel').then(async excel =>{

        // 获取所有员工列表
       const { rows } = await getEmployeesList({page:1,size:this.page.total})
       const data = this.formatJSON(headers,rows)
        //excel导出的默认对象
        excel.export_json_to_excel({
          filename:'员工数据表',
          header:Object.keys(headers),
          multiHeader: [['姓名','主要信息','','','','','部门']], // 复杂表头导出 数组中的每个数组就是一行表头
          data,
          merges:['A1:A2','B1:F1','G1:G2'] //合并列 不区分顺序，只写合并单元格的序号
        })
      })
    },
    // 格式化json数据
    formatJSON(headers ,rows){
      // 数据的顺序按照key的顺序来
      // rows [{},{}]  => [[],[]]
      return rows.map(item=>{
        // item  {username:'' , mobile:1123 ,...}
        // Object.keys(headers) ['姓名', '手机号', ...]
         return Object.keys(headers).map(key =>{

          if( headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime'){
            // 格式化时间格式
            return formatDate(item[headers[key]])

          }else if( headers[key] === 'formOfEmployment'  ){
            // 格式化聘用形式 
            const obj = EmployeeEnum.hireType.find( e => e.id === item[headers[key]]);

            return obj ? obj.value : "未知";
          }
          return item[headers[key]]
          
        })
        
      })

    //  return rows.map(item =>Object.keys(headers).map(key=>item[headers[key]]))

    },
    // 删除员工
    delEmployee(id) {
      this.$confirm("确定删除该员工吗？")
        .then(() => {
          // console.log(id);
          return delEmployee(id);
        })
        .then(() => {
          this.$message.success("删除成功");
          this.getEmployeesList();
        });
    },
    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      // console.log(arguments);
      // cellValue 当前单元格的值 row 当前行的数据对象
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue);

      return obj ? obj.value : "未知";
    },
    // 获取员工信息
    async getEmployeesList() {
      this.loading = true;
      const { total, rows } = await getEmployeesList(this.page);
      this.page.total = total;
      this.list = rows;
      this.loading = false;
    },
    async asingRole(id) {
      this.userId = id
      await this.$refs.asignRole.getUserDetailById(id)
      this.showRoleDialog = true
    }
  },
};
</script>

<style scoped lang='less'></style>